namespace Behaving.Composites
{
    public abstract class CompositeExtended : Composite
    {
        private int? _runningChildNumber;
        protected CompositeExtended(params Behaviour[] children)
            : base(children)
        {
        }

        protected abstract RunningState AfterSequenceState { get; }

        public override RunningState Execute(BehaviourTree behaviourTree)
        {
            int startWith = _runningChildNumber ?? 0;
            _runningChildNumber = null;

            for (int i = startWith; i < Children.Count; i++)
            {
                Behaviour behaviour = Children[i];
                RunningState runningState = behaviour.Tick(behaviourTree);

                if (runningState == RunningState.Running)
                {
                    _runningChildNumber = i;
                    return runningState;
                }

                if (SequenceDone(runningState))
                {
                    return RunningState.Success;
                }
            }
            return AfterSequenceState;
        }

        protected abstract bool SequenceDone(RunningState runningState);
    }
}